package cn.bugstack.mybatis.bindings;

import cn.bugstack.mybatis.session.Configuration;
import cn.bugstack.mybatis.session.SqlSession;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MapperRegistry {

    private Configuration configuration;

    private final Map<Class<?>, MapperProxyFactory<?>> knowMappers = new ConcurrentHashMap<>();

    public MapperRegistry(Configuration configuration) {
        this.configuration = configuration;
    }


    public <T> boolean hasMapper(Class<T> mapperInterface) {
        return knowMappers.containsKey(mapperInterface);
    }

    public void addMapper(Class<?> mapperInterface) {
        if (mapperInterface.isInterface()) {
            if (hasMapper(mapperInterface)) {
                throw new RuntimeException("Type " + mapperInterface + "is already known to MapperRegistry.");
            }
            knowMappers.put(mapperInterface, new MapperProxyFactory<>(mapperInterface));
        }
    }

    public <T> T getMapper(Class<T> mapperInterface, SqlSession sqlSession) {
        MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knowMappers.get(mapperInterface);
        if (mapperProxyFactory == null) {
            throw new RuntimeException("Type "+mapperInterface+ "is not known to MapperRegistry.");
        }
        if (hasMapper(mapperInterface)) {
            return mapperProxyFactory.newInstance(sqlSession);
        }
        return null;
    }
}
